package com.nativetalk.service.three.message;

import com.nativetalk.base.Page;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberDetail;
import com.nativetalk.bean.message.TdNtMessageInsert;
import com.nativetalk.bean.message.TdNtMessageList;
import com.nativetalk.bean.message.system.TdNtSystemMessage;
import com.nativetalk.bean.message.system.TdNtSystemMessageMarker;
import com.nativetalk.bean.teacher.TdNtTeacherGetui;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.getui.AndroidMessageStudent;
import com.nativetalk.common.getui.AndroidMessageTeacher;
import com.nativetalk.common.getui.IosMessageStudent;
import com.nativetalk.common.getui.IosMessageTeacher;
import com.nativetalk.dao.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 16/7/6.
 */
@Service
public class MessageServiceImpl implements MessageService {
    private static Logger logger = Logger.getLogger(MessageServiceImpl.class);
    @Resource
    private TdNtMessageDao tdNtMessageDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtSystemMessageDao tdNtSystemMessageDao;
    @Resource
    private TdNtCommentDao tdNtCommentDao;

    /**
     * @param tdNtMember
     * @param type       1:学生发消息，2:老师读取消息
     * @return RetInfo
     * @Purpose 学生发消息, 老师收消息
     * @version 3.0
     * @author lizhun
     */
    @Override
    public synchronized RetInfo sendMembMessage(TdNtMember tdNtMember, int type,
                                                TdNtMessageInsert tdNtMessageInsert, TdNtTeacherResult tdNtTeacherResult) {
        String logInfo = this.getClass().getName() + ":sendMembMessage:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            tdNtMessageInsert.setUser_type(1);
            if (type == 1) {
                /**
                 * 学生发消息
                 */
                int size = 0;
                tdNtMessageInsert.setUser_id(tdNtMember.getMemb_id());
                tdNtMessageInsert.setMes_type(1);
                TdNtMessageInsert message = tdNtMessageDao.findTdNtMessageInsert(tdNtMessageInsert);
                if (message != null) {
                    size = message.getNot_read_size() + 1;
                    message.setEnd_update_time(new Timestamp(System.currentTimeMillis()));
                    message.setNot_read_size(size);
                    message.setMes_type(1);
                    tdNtMessageDao.updateTdNtMessage(message);
                    size = message.getNot_read_size() + 1;
                } else {
                    tdNtMessageInsert.setEnd_update_time(new Timestamp(System.currentTimeMillis()));
                    tdNtMessageInsert.setNot_read_size(1);
                    tdNtMessageInsert.setMes_type(1);
                    tdNtMessageDao.insertTdNtMessage(tdNtMessageInsert);
                    size = 1;
                }
                /**
                 * 发送消息 推送
                 */
                TdNtTeacherGetui teacher = tdNtTeacherDao.findTdNtTeacher(tdNtMessageInsert.getCollect_user_id());
                if (teacher == null) {
                    logger.error("老师不存在，tea_id:" + tdNtMessageInsert.getCollect_user_id());
                }

                if (teacher.getEqu_type().equals(Constants.equ_type_android)) {
                    AndroidMessageTeacher.apnpush("NativeTalk", tdNtMember.getMemb_name() + ":" + tdNtMessageInsert.getContent()
                            , teacher.getEqu_client_id(), tdNtMessageInsert.getUser_id(), tdNtMember.getMemb_name(), tdNtMember.getMemb_head_portrait(), size);
                } else {
                    TdNtMessageInsert messageInsert = new TdNtMessageInsert();
                    messageInsert.setCollect_user_id(tdNtMessageInsert.getCollect_user_id());
                    messageInsert.setUser_type(tdNtMessageInsert.getUser_type());
                    messageInsert.setMes_type(1);
                    int total_size = tdNtMessageDao.findMessageSize(messageInsert);
                    IosMessageTeacher.apnpush("NativeTalk", tdNtMember.getMemb_name() + ":" + tdNtMessageInsert.getContent()
                            , teacher.getEqu_client_id(), tdNtMessageInsert.getUser_id(), tdNtMember.getMemb_name(), tdNtMember.getMemb_head_portrait(), size, total_size + 1);
                }
            } else {
                /**
                 * 老师收消息
                 */
                tdNtMessageInsert.setCollect_user_id(tdNtTeacherResult.getTea_id());
                TdNtMessageInsert message = tdNtMessageDao.findTdNtMessageInsert(tdNtMessageInsert);
                int notReadMsgSize = message == null ? 0 : message.getNot_read_size();
                TdNtTeacherGetui teacher = tdNtTeacherDao.findTdNtTeacher(tdNtMessageInsert.getCollect_user_id());
                if (teacher == null) {
                    logger.error("老师不存在，tea_id(Collect_user_id):" + tdNtMessageInsert.getCollect_user_id());
                }

                if (teacher.getEqu_type().equals(Constants.equ_type_ios)) {
                    TdNtMessageInsert messageInsert = new TdNtMessageInsert();
                    messageInsert.setCollect_user_id(tdNtMessageInsert.getCollect_user_id());
                    messageInsert.setUser_type(tdNtMessageInsert.getUser_type());
                    int total_size = tdNtMessageDao.findMessageSize(messageInsert);
                    IosMessageTeacher.apnpushBadge(teacher.getEqu_client_id(), total_size - notReadMsgSize);
                }

                message.setEnd_update_time(new Timestamp(System.currentTimeMillis()));
                message.setNot_read_size(0);
                tdNtMessageDao.updateTdNtMessage(message);
            }
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("成功");

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public synchronized RetInfo collectMembMessage(TdNtMember tdNtMember, int type,
                                                   TdNtMessageInsert tdNtMessageInsert, TdNtTeacherResult tdNtTeacherResult) {
        String logInfo = this.getClass().getName() + ":collectMembMessage:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            tdNtMessageInsert.setUser_type(2);
            if (type == 1) {
                /**
                 * 教师发消息
                 */
                tdNtMessageInsert.setUser_id(tdNtTeacherResult.getTea_id());
                TdNtMessageInsert message = tdNtMessageDao.findTdNtMessageInsert(tdNtMessageInsert);
                int size = 0;
                if (message != null) {
                    message.setEnd_update_time(new Timestamp(System.currentTimeMillis()));
                    message.setNot_read_size(message.getNot_read_size() + 1);
                    tdNtMessageDao.updateTdNtMessage(message);
                    size = message.getNot_read_size() + 1;
                } else {
                    tdNtMessageInsert.setEnd_update_time(new Timestamp(System.currentTimeMillis()));
                    tdNtMessageInsert.setNot_read_size(1);
                    tdNtMessageDao.insertTdNtMessage(tdNtMessageInsert);
                    size = 1;
                }
                /**
                 * 发送消息 推送
                 */
                TdNtMemberDetail member = tdNtMemberDao.findTdNtMemberDetail(tdNtMessageInsert.getCollect_user_id());
                if (member.getEqu_type().equals("1")) {
                    AndroidMessageStudent.apnpush("NativeTalk", tdNtTeacherResult.getTea_name() + ":" + tdNtMessageInsert.getContent()
                            , member.getEqu_client_id(), tdNtMessageInsert.getUser_id(), tdNtTeacherResult.getTea_name(), tdNtTeacherResult.getTea_head_portrait(), size);
                } else {
                    TdNtMessageInsert messageInsert = new TdNtMessageInsert();
                    messageInsert.setCollect_user_id(tdNtMessageInsert.getCollect_user_id());
                    messageInsert.setUser_type(tdNtMessageInsert.getUser_type());
                    int total_size = tdNtMessageDao.findMessageSize(messageInsert);
                    IosMessageStudent.apnpush("NativeTalk", tdNtTeacherResult.getTea_name() + ":" + tdNtMessageInsert.getContent()
                            , member.getEqu_client_id(), tdNtMessageInsert.getUser_id(), tdNtTeacherResult.getTea_name(), tdNtTeacherResult.getTea_head_portrait(), size, total_size + 1);
                }
            } else {
                /**
                 * 学生收消息
                 */
                tdNtMessageInsert.setCollect_user_id(tdNtMember.getMemb_id());
                TdNtMessageInsert message = tdNtMessageDao.findTdNtMessageInsert(tdNtMessageInsert);
                if (message != null) {
                    TdNtMemberDetail member = tdNtMemberDao.findTdNtMemberDetail(tdNtMessageInsert.getCollect_user_id());
                    if (member.getEqu_type().equals("2")) {
                        TdNtMessageInsert messageInsert = new TdNtMessageInsert();
                        messageInsert.setCollect_user_id(messageInsert.getCollect_user_id());
                        messageInsert.setUser_type(tdNtMessageInsert.getUser_type());
                        int total_size = tdNtMessageDao.findMessageSize(tdNtMessageInsert);
                        IosMessageStudent.apnpushBadge(member.getEqu_client_id(), total_size - message.getNot_read_size());
                    }
                    message.setEnd_update_time(new Timestamp(System.currentTimeMillis()));
                    message.setNot_read_size(0);
                }

                tdNtMessageDao.updateTdNtMessage(message);
            }
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("成功");

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findMessageSize(TdNtMessageInsert tdNtMessageInsert, int version) {
        String logInfo = this.getClass().getName() + ":findMessageSize:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            /**
             * 获取消息未读条数
             */
            int size = tdNtMessageDao.findMessageSize(tdNtMessageInsert);
            System.out.println("size" + size);
            if (version >= 8) {
                /**
                 * 获取系统消息未读条数
                 */
                Page page = new Page();
                page.setObj(tdNtMessageInsert.getCollect_user_id());
                if (tdNtMessageInsert.getUser_type() == 1) {
                    page.setDict_id(2);
                } else {
                    page.setDict_id(1);
                }
                page.setMes_type(1);
                TdNtSystemMessageMarker tdNtSystemMessageMarker = tdNtSystemMessageDao.findTdNtSystemMessageMarker(page);

                if (tdNtSystemMessageMarker != null) {
                    int system_size = tdNtSystemMessageDao.findSystemMessageSizeByTime(page,tdNtSystemMessageMarker.getRead_time());
                    size += system_size;
                } else {
                    int system_size = tdNtSystemMessageDao.findSystemMessageSize(page);
                    size += system_size;
                }

                page.setMes_type(2);
                TdNtSystemMessageMarker tdNtSystemMessageMarker1 = tdNtSystemMessageDao.findTdNtSystemMessageMarker(page);
                if (tdNtSystemMessageMarker1 != null) {
                    int system_size = tdNtReserveDao.findTdNtReserverSuccessSize(page,tdNtSystemMessageMarker1.getRead_time());
                    size += system_size;
                }
            }
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("成功");
            retInfo.setObj(size);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Resource
    private TdNtReserveDao tdNtReserveDao;

    @Override
    public RetInfo findMessagePage(Map<String, Object> map, int version) {
        String logInfo = this.getClass().getName() + ":findMessagePage:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            int currentPage = Integer.valueOf(map.get("currentPage").toString());
            int pageSize = 10;//每页数据
            int totalPage;//总页数
            map.put("mes_type",1);
            int totalRecord = tdNtMessageDao.findMessageListSize(map);//总条数
            Map<String, Object> obj = new HashMap<String, Object>();
            Page page = new Page();
            if (map.get("user_type").equals(1)) {
                obj.put("member", Constants.member);
                page.setDict_id(2);
            } else {
                obj.put("teacher", Constants.teacher);
                page.setDict_id(1);
            }

            if (version >= 8) {
                /**
                 * 获取系统消息未读条数
                 */

                page.setObj(map.get("collect_user_id"));
                page.setMes_type(1);
                TdNtSystemMessageMarker tdNtSystemMessageMarker = tdNtSystemMessageDao.findTdNtSystemMessageMarker(page);
                int system_size;
                if (tdNtSystemMessageMarker != null) {
                    system_size = tdNtSystemMessageDao.findSystemMessageSizeByTime(page,tdNtSystemMessageMarker.getRead_time());
                } else {
                    system_size = tdNtSystemMessageDao.findSystemMessageSize(page);
                }
                obj.put("system_size", system_size);
                //未读评价数
                page.setMes_type(2);
                TdNtSystemMessageMarker tdNtSystemMessageMarker1 = tdNtSystemMessageDao.findTdNtSystemMessageMarker(page);
                int comment_size = 0;
                if (tdNtSystemMessageMarker1 != null) {
                    comment_size = tdNtReserveDao.findTdNtReserverSuccessSize(page,tdNtSystemMessageMarker1.getRead_time());
                } 
                obj.put("comment_size",comment_size);
                page.setCurrentPage(0);
                page.setPageSize(1);
                List<TdNtSystemMessage> tdNtSystemMessages = tdNtSystemMessageDao.findSystemMessage(page);
                if (tdNtSystemMessages != null && tdNtSystemMessages.size() > 0) {
                    obj.put("system_title", tdNtSystemMessages.get(0).getSys_mes_title());
                    obj.put("system_publish_time", tdNtSystemMessages.get(0).getSys_publish_time());
                } else {
                    obj.put("system_title", "暂无系统消息");
                }
            }
            if (totalRecord > 0) {
                if (totalRecord % pageSize == 0) {
                    totalPage = totalRecord / pageSize;
                } else {
                    totalPage = (totalRecord / pageSize) + 1;
                }
                if (currentPage >= totalPage) {
                    currentPage = totalPage;
                }
                if (currentPage <= 1) {
                    currentPage = 1;
                }
                map.put("currentPage", (currentPage - 1) * pageSize);
                map.put("pageSize", pageSize);
                map.put("mes_type",1);
                List<TdNtMessageList> list = tdNtMessageDao.findMessageList(map);

                obj.put("messages", list);
                obj.put("totalPage", totalPage);


                retInfo.setMark("0");
                retInfo.setTip("获取消息成功");
                retInfo.setObj(obj);
            } else {
                retInfo.setMark("1");
                retInfo.setTip("暂无未读消息");
                retInfo.setObj(obj);
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findSystemMessage(Page page) {
        String logInfo = this.getClass().getName() + ":findSystemMessage:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Object> result = new HashMap<>();
            int currentPage = page.getCurrentPage();
            int pageSize = page.getPageSize();
            int totalPage;//总页数
            int totalRecord = tdNtSystemMessageDao.findSystemMessageSize(page);//总条数
            if (totalRecord > 0) {
                if (totalRecord % pageSize == 0) {
                    totalPage = totalRecord / pageSize;
                } else {
                    totalPage = (totalRecord / pageSize) + 1;
                }
                if (currentPage >= totalPage) {
                    currentPage = totalPage;
                }
                if (currentPage <= 1) {
                    page.setCurrentPage(1);
                }
                page.setCurrentPage((page.getCurrentPage() - 1) * pageSize);
                List<TdNtSystemMessage> tdNtSystemMessages = tdNtSystemMessageDao.findSystemMessage(page);
                TdNtSystemMessageMarker tdNtSystemMessageMarker = tdNtSystemMessageDao.findTdNtSystemMessageMarker(page);
                if (tdNtSystemMessageMarker != null) {
                    page.setObj(tdNtSystemMessageMarker.getRead_time());
                    tdNtSystemMessageMarker.setMes_type(1);
                    tdNtSystemMessageDao.updateSystemMessageMarker(tdNtSystemMessageMarker);
                } else {
                    tdNtSystemMessageMarker = new TdNtSystemMessageMarker();
                    tdNtSystemMessageMarker.setUser_id(Integer.valueOf(page.getObj().toString()));
                    tdNtSystemMessageMarker.setUser_type(Integer.valueOf(page.getDict_id().toString()));
                    tdNtSystemMessageMarker.setMes_type(1);
                    tdNtSystemMessageDao.insertSystemMessageMarker(tdNtSystemMessageMarker);
                }
                result.put("systemMessages", tdNtSystemMessages);
                result.put("totalPage", totalPage);

                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("获取列表成功");
                retInfo.setObj(result);

            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("暂无系统消息");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
